import { defineStore } from "pinia";

export const useStore=defineStore('cart',{
    state:()=>{
        return {
            cart:[]
        }
    },
    getters:{
        total(state){
            return state.cart.reduce((total,i)=>total+=i.price*i.count,0)
        },
        count(state){
            return state.cart.reduce((total,i)=>total+=i.count,0)
        }
    },
    actions:{
        addProduct(v){
            let id=this.cart.findIndex(item=>item.id===v.id)
            if(id===-1){
                v.count=1
                this.cart.push(v)
            }else{
                this.cart[id].count++
            }        
        },
        reduceProduct(id){
            let index=this.cart.findIndex(item=>item.id===id)
            this.cart.splice(index,1)
        }
    },
    persist:{
        enabled:true,
        strategies:[
            {
                key:'cart',
                storage:sessionStorage
            }
        ]
    }
})